package com.didi.gulimall.order.service.impl;

import com.didi.gulimall.common.constant.OrderStatusEnum;
import com.didi.gulimall.common.utils.LogUtils;
import com.didi.gulimall.common.utils.R;
import com.didi.gulimall.config.AlipayTemplate;
import com.didi.gulimall.order.entity.OrderEntity;
import com.didi.gulimall.order.service.OrderService;
import com.didi.gulimall.order.service.PayWebService;
import com.didi.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 10626
 * @Create 2021/6/7 13:16
 */
@Service
@Slf4j
public class PayWebServiceImpl implements PayWebService {
    @Value("${gulimall.home}")
    private String homeHtml;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Override
    public String patOrder(String orderSn) {
        OrderEntity orderEntity = orderService.getIdByOrderSn(orderSn);
        if (orderEntity == null || !orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            return "redirect:" + homeHtml;
        }
        try {
            String pay = alipayTemplate.pay(orderEntity);
            if (StringUtils.isEmpty(pay)) {
                return "redirect:" + homeHtml;
            }
            return pay;
        } catch (Exception e) {
            log.error(LogUtils.getStackTraceInfo(e));
            return "redirect:" + homeHtml;
        }
    }

    @Override
    public String asynchronousNotification(PayAsyncVo payAsyncVo, HttpServletRequest request) throws Exception {
        try {
            Boolean flg = alipayTemplate.verifyNotify(payAsyncVo, request);
            if (flg) {
                orderService.paymentSuccessful(payAsyncVo);
            }
            return "success";
        } catch (Exception e) {
            log.error(LogUtils.getStackTraceInfo(e));
            return "fail";
        }
    }

    @Override
    public R queryAlpayTrade(String orderSn) throws Exception {
        Boolean query = alipayTemplate.query(orderSn);
        return query ? R.ok().put("msg", "订单支付成功") : R.ok().put("msg", "订单未支付");
    }

    @Override
    public R cancelAlpayTrade(String orderSn) throws Exception {
        alipayTemplate.cancel(orderSn);
        return R.ok();
    }
}
